package thss.mro.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 快速查询测试
 */
public class QueryTester {

	private static HashMap<String,String> filterNameMap = new HashMap<String,String>();
	
	public QueryTester(){
		filterNameMap.put("templateField", "");
	}
	
	/**
	 * 查询测试主程序
	 */
	public static void main(String[] args) {
		Map obj = new HashMap();	//更换这里的代码，获得查询返回的结果
		int i=1;
		obj.put("key0", i);

		obj.put("key1", "value1");
		obj.put("key2", 2);
		obj.put("key3", new String[]{"1","2"});
		List key4 = new ArrayList();
		key4.add(1);
		key4.add("xxxx");
		obj.put("key4", key4);
		try{
			QueryTester qt = new QueryTester();
			//开始解析对象结果	
//			int newDeep = 0; //当前深度，刚开始固定为0
			int maxDeep = 2; //解析深度，所要往下解析的最大深度。如对象嵌套或List嵌套这些情况可以解析出深层的值或对象
			qt.parseObject(obj, maxDeep);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static String getaAheadString(int deep){
		StringBuffer tmp = new StringBuffer();
		while(deep>0){
			tmp.append("----");
			deep--;
		}
		return tmp.toString();
	}
	
	/**
	 * 递归解析，deep为解析深度
	 * @param obj
	 * @param deep
	 */
	public static void parseObject(Object obj , int maxDeep) {
		System.out.println("================================QueryTester START================================");
		parseObject(obj,0,maxDeep);
		System.out.println("================================QueryTester END================================");
	}
	
	/**
	 * 递归解析，deep为解析深度
	 * @param obj
	 * @param deep
	 */
	private static void parseObject(Object obj , int deep , int maxDeep) {
		
		//为空，直接打印对象并返回
		if(obj==null ){	
			System.out.println("[(类型：null) "+obj+" ]");
			return;
		}else if(obj instanceof String ){	
			System.out.println("[(类型："+obj.getClass().getName()+") "+obj+" ]");
			return;
		}else if(obj instanceof String[] ){	
			int objSize = ((String[])obj).length;
			System.out.print("[(类型："+obj.getClass().getName()+") ");
			for(int i=0;i<objSize;i++){
				System.out.print(((String[])obj)[i]+";");
			}
			System.out.println(" ]");
			return;
		}else if(obj instanceof byte[] ){
			byte[] tmp =(byte[])obj;
			System.out.print("[(类型：byte[] ) ");
			printHexString(tmp);
			System.out.println(" ]");
			return;
		}
		try{
			if(((Class)obj.getClass().getField("TYPE").get(null)).isPrimitive()){	//基本数据类型封装类时
				System.out.println("[(类型："+obj.getClass().getName()+")"+obj+" ]");
				return;
			}
		}catch(NoSuchFieldException e){
			System.out.println("[(类型："+obj.getClass().getName()+")]");
			//不是基本类型封装类
			Iterator it = null;
			if(obj instanceof List){
				it = ((List)obj).iterator();
			}else if(obj instanceof Set){
				it = ((Set)obj).iterator();
			}else if(obj instanceof Map){
				it = ((Map)obj).keySet().iterator();
				while(it.hasNext()){
					String key = (String)it.next();
					System.out.print(getaAheadString(deep+1)+key+"=");
					parseObject(((Map)obj).get(key),deep+1,maxDeep-1);
				}
			}else {
				//非集合类则直接解析Object对象
				try {
					subParseObject(obj, deep+1 , maxDeep);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				return;
			}
//			++deep;
			while(it.hasNext()){
				System.out.print(getaAheadString(deep+1));
				parseObject(it.next(),deep+1,maxDeep);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void subParseObject(Object obj, int deep , int maxDeep) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException{
		//获得对象的类型    
        Class classType=obj.getClass();    
        //System.out.println("对象："+classType.getName());    
        
        //获得对象的所有属性    
        Field[] fields=classType.getDeclaredFields();    
            
        for(int i=0;i<fields.length;i++){
            //获取数组中对应的属性    
            Field field=fields[i];
            String fieldName=field.getName();    
            String stringLetter=fieldName.substring(0, 1).toUpperCase();    
                
            //获得相应属性的getXXX方法名称    
            String getName="get"+stringLetter+fieldName.substring(1);    
            
            //获取相应的方法    
            Method getMethod = null;
            try{
            	getMethod=classType.getMethod(getName, new Class[]{});    
            }catch(NoSuchMethodException e){
            	try{
            		getName = getName.substring(3);
            		getName = getName.substring(0, 1).toLowerCase()+getName.substring(1);
            		getMethod=classType.getMethod(getName, new Class[]{}); 
            	}catch(NoSuchMethodException e1){
            		try{
            			getName = "is"+getName;
            			getMethod=classType.getMethod(getName, new Class[]{}); 
            		}catch(Exception e2){
            			return;
            		}
            	}
            }
            //调用源对象的getXXX（）方法    
            Object value=getMethod.invoke(obj, new Object[]{});    
            if(deep<=maxDeep){
            	System.out.print(getaAheadString(deep)+ fieldName +" : ");
            	if(!filterNameMap.containsKey(fieldName)){
            		parseObject(value,deep,maxDeep);
            	}
            }else{
            	System.out.println(getaAheadString(deep)+ fieldName+" : "+value);    
            }
        }
	}

	//将指定byte数组以16进制的形式打印到控制台   
	public static void printHexString( byte[] b) {     
	   for (int i = 0; i < b.length; i++) {    
	     String hex = Integer.toHexString(b[i] & 0xFF);    
	     if (hex.length() == 1) {    
	       hex = '0' + hex;    
	     }    
	     System.out.print(hex.toUpperCase() );    
	   }    
//	   System.out.println();
	}  

}